import { httpPost } from "./utils/httpPost";
import { setFileLog } from "./utils/setFileLog";
import { useDeviceUuid } from "./utils/useDeviceUuid";
import { useStorage } from "./utils/useStorage";

/**
 * 执行项目
 * @param path 项目路径
 * @returns 
 */
function execProject(path: string) {
    const packageJson = files.join(path, 'package.json')
    if (files.exists(packageJson)) {
        const content = files.read(packageJson, 'utf-8')
        const project = JSON.parse(content)
        const mainFile = files.join(path, project.main)
        if (files.exists(mainFile)) {
            engines.all().forEach((item) => {
                if (item.getSource() == mainFile) item.forceStop()
            });
            const script = engines.execScriptFile(mainFile, {
                path: path
            });
            script.getEngine();
            toastLog(`恭喜您，启动成功,${project.name}`)
            return;
        }
        throw new Error(`no ${project.main} exisit`)
    }
    throw new Error(`no package.json exisit`)
}
/**
 * name 应用
 * title 名称
 * icon 图标
 * version 版本号
 * autor 作者
 * url 下载地址  http://xxxx/name-version.zip
 * @param url 
 */
function checkPackage(name: string) {
    const SD = files.getSdcardPath()
    const root = files.join(SD, 'sker');
    files.ensureDir(root)
    const downloadDir = files.join(root, 'downloads')
    files.ensureDir(downloadDir)

    const dirPath = files.join(root, `modules/`)
    files.ensureDir(dirPath)

    const packageInfo = httpPost('client/checkPackage', { name, uuid: useDeviceUuid() })
    const storage = useStorage()
    const version = storage.get(`${name}.version`)
    if (version !== packageInfo.version) {
        toastLog(`存在最新版本${packageInfo.version},正在更新...`)
        // 去下载地址下载
        const download = http.get(packageInfo.url) as AutoJs.Response;
        if (download.statusCode === 200) {
            const filePath = files.join(downloadDir, `${name}-${packageInfo.version}.zip`)
            files.createWithDirs(filePath)
            files.writeBytes(filePath, download.body.bytes())
            toastLog(`下载完成,正在解压并安装...`)
            const zipFile = $zip.open(filePath)
            if (!zipFile.isValidZipFile()) {
                throw new Error(`无效zip文件`)
            }
            if (zipFile.isEncrypted()) {
                throw new Error(`文件已加密`)
            }
            zipFile.extractAll(dirPath)
            storage.put(`${name}.version`, packageInfo.version)
            toastLog(`更新并安装完成`)
            return files.join(dirPath, name);
        }
        throw new Error(`下载失败`)
    } else {
        return files.join(dirPath, `${name}`);
    }
}

function render() {
    ui.layout(`<frame w="*" h="*">
        <text layout_gravity="center" id="loading" w="auto" h="auto" text="加载中..." textSize="16sp" textColor="#333333"/>
    </frame>`)
}

try {
    render()
    const date = new Date()
    setFileLog(`log-${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`)
    threads.start(function () {
        try {
            execProject(checkPackage('cloud'))
        } catch (e) {
            console.error(e)
            console.log((e as Error).toString())
            ui.run(() => {
                ui.findView('loading').text("启动失败,请联系系统管理员")
                toastLog(`启动失败,请联系系统管理员`)
            })
        }
    })
} catch (e) {
    console.error(e)
    console.log((e as Error).toString())
    ui.findView('loading').text("启动失败,请联系系统管理员")
    toastLog(`启动失败,请联系系统管理员`)
}
